<template>
	<view class="category-container">
		<!-- 搜索栏 -->
		<view class="search-bar" style="position: relative;">
			<uni-search-bar :placeholder="searchPlaceholder" @confirm="handleSearch" @input="handleSearchInput"
				@clear="handleClearSearch" :showCancel="false" cancelText="搜索" @cancel="handleSearch"
				@focus="handleSearchFocus" @blur="handleSearchBlur" />
			<!-- 搜索历史记录 -->
			<view class="search-history" v-if="showHistory && searchHistory.length > 0"
				style="position: absolute; top: 110%; left: 0; right: 0; z-index: 9999;">
				<view class="history-title">
					<text>搜索历史</text>
					<uni-icons type="trash" size="18" @click="clearSearchHistory"></uni-icons>
				</view>
				<view class="history-list">
					<view class="history-item" v-for="(item, index) in searchHistory" :key="index"
						@click="selectHistoryItem(item)">
						{{ item }}
					</view>
				</view>
			</view>
		</view>

		<!-- 一级分类导航 -->
		<scroll-view class="first-category" scroll-x>
			<view class="category-item" v-for="(item, index) in displayedFirstCategories" :key="item.typeFirstId"
				:class="{ active: activeFirstCategoryId === item.typeFirstId }"
				@click="changeFirstCategory(item.typeFirstId, index)">
				<image :src="getCategoryIcon(item.nameFirst)" class="category-icon"></image>
				<text class="category-name">{{ item.nameFirst }}</text>
			</view>
			<view class="category-item all-category" @click="showAllCategories">
				<image src="/static/images/all.png" class="category-icon"></image>
				<text class="category-name">全部</text>
			</view>
		</scroll-view>

		<!-- 二级分类和商品展示 -->
		<view class="content-container">
			<!-- 二级分类导航 -->
			<scroll-view class="second-category" scroll-y>
				<view class="second-item recommend-item" :class="{ active: activeSecondCategoryId === 'recommend' }"
					@click="changeSecondCategory('recommend')">
					推荐
				</view>
				<view class="second-item all-item" :class="{ active: activeSecondCategoryId === 'all' }"
					@click="changeSecondCategory('all')">
					全部
				</view>
				<view class="second-item" v-for="item in currentSecondCategories" :key="item.typeSecondId"
					:class="{ active: activeSecondCategoryId === item.typeSecondId }"
					@click="changeSecondCategory(item.typeSecondId)">
					{{ item.nameSecond }}
				</view>
			</scroll-view>

			<!-- 商品展示 - 单列布局 -->
			<scroll-view class="goods-list" scroll-y>
				<!-- 推荐商品 -->
				<view class="section" v-if="activeSecondCategoryId === 'recommend'">
					<text class="section-title">推荐商品</text>
					<view class="goods-column">
						<view class="goods-item" v-for="item in recommendedGoods" :key="item.id"
							@click="goToDetail(item.id)">
							<image :src="item.imgSrc" class="goods-image"></image>
							<view class="goods-info">
								<text class="goods-name">{{ item.name }}</text>
								<text class="goods-reason" v-if="item.reason">{{ item.reason }}</text>
								<view class="price-container">
									<text class="original-price" v-if="item.originPrice">¥{{ item.originPrice }}</text>
									<text class="current-price">¥{{ item.price }}</text>
								</view>
							</view>
							<view class="cart-icon" @click.stop="addToCart(item)">
								<uni-icons type="cart" size="24" color="#ff6700"></uni-icons>
							</view>
						</view>
					</view>
				</view>

				<!-- 分类商品 -->
				<view class="section" v-else>
					<text class="section-title">{{ currentSecondCategoryName }}</text>
					<view class="goods-column">
						<view class="goods-item" v-for="item in currentGoodsList" :key="item.id"
							@click="goToDetail(item.id)">
							<image :src="item.imgSrc" class="goods-image"></image>
							<view class="goods-info">
								<text class="goods-name">{{ item.name }}</text>
								<text class="goods-reason" v-if="item.reason">{{ item.reason }}</text>
								<view class="price-container">
									<text class="original-price" v-if="item.originPrice">¥{{ item.originPrice }}</text>
									<text class="current-price">¥{{ item.price }}</text>
								</view>
							</view>
							<view class="cart-icon" @click.stop="addToCart(item)">
								<uni-icons type="cart" size="24" color="#ff6700"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import request from '../../utils/request';
import {
		getGoodsList,
		getGoodsCategories
	} from '@/api/goods';
	import {
		saveSearchHistory,
		getSearchHistory
	} from '@/api/search';

	export default {
		data() {
			return {
				searchPlaceholder: '', // 搜索框placeholder
				allCategories: [], // 所有分类数据
				allFirstCategories: [], // 所有一级分类
				displayedFirstCategories: [], // 显示的一级分类(前5个)
				currentSecondCategories: [], // 当前一级分类下的二级分类
				recommendedGoods: [], // 推荐商品
				currentGoodsList: [], // 当前分类商品列表
				activeFirstCategoryId: null, // 当前选中一级分类ID
				activeSecondCategoryId: 'recommend', // 当前选中二级分类ID
				currentSecondCategoryName: '推荐', // 当前二级分类名称
				searchKeyword: '', // 搜索关键词
				showHistory: false, // 是否显示搜索历史
				searchHistory: [], // 搜索历史记录
				userId: 3 // 临时用户ID
			};
		},
		async created() {
			await this.loadAllCategories();
			this.setSearchPlaceholder();
			await this.loadSearchHistory();

			// 加载搜索历史记录
			await this.loadSearchHistory();

			// 默认选中第一个一级分类，并加载其推荐商品
			if (this.allFirstCategories.length > 0) {
				await this.changeFirstCategory(this.allFirstCategories[0].typeFirstId, 0);
				this.activeSecondCategoryId = 'recommend'; // 默认显示推荐
				await this.loadCurrentRecommendGoods(); // 加载当前分类的推荐商品
			}
		},
		onLoad() {
			uni.$on('categoryChange', this.handleCategoryChange);
		},
		onUnload() {
			uni.$off('categoryChange', this.handleCategoryChange);
		},
		methods: {
			//加载主页跳转数据
			handleCategoryChange(data) {
				if (data.typeFirstId) {
					const index = this.allFirstCategories.findIndex(
						item => item.typeFirstId === data.typeFirstId
					);
					if (index !== -1) {
						this.changeFirstCategory(data.typeFirstId, index);
					}
				}
			},
			async loadCurrentRecommendGoods() {
				try {
					const params = {
						param: {
							typeFirstId: this.activeFirstCategoryId,
							recommend: 1,
							status: 1
						}
					};

					const res = await getGoodsList(params);
					if (res.code === 200) {
						this.recommendedGoods = res.data.map(this.formatGoodsItem); // 直接使用data而不是data.list
					}
				} catch (error) {
					console.error('加载推荐商品失败:', error);
					this.recommendedGoods = [];
				}
			},

			// 加载所有分类数据
			async loadAllCategories() {
				try {
					const res = await getGoodsCategories();
					if (res.code === 200) {
						this.allCategories = res.data;

						// 提取一级分类(去重)
						const firstCategoriesMap = new Map();
						res.data.forEach(item => {
							if (!firstCategoriesMap.has(item.typeFirstId)) {
								firstCategoriesMap.set(item.typeFirstId, {
									typeFirstId: item.typeFirstId,
									nameFirst: item.nameFirst
								});
							}
						});

						this.allFirstCategories = Array.from(firstCategoriesMap.values());
						this.displayedFirstCategories = this.allFirstCategories.slice(0, 5);
					}
				} catch (error) {
					console.error('加载分类失败:', error);
				}
			},

			// 加载推荐商品
			async loadRecommendedGoods() {
				try {
					const params = {
						pageNum: null,
						pageSize: null,
						param: {
							recommend: 1,
							status: 1 // 只查询上架商品
						}
					};

					const res = await getGoodsList(params);
					if (res.code === 200) {
						this.recommendedGoods = res.data.list.map(this.formatGoodsItem);
					}
				} catch (error) {
					console.error('加载推荐商品失败:', error);
				}
			},

			// 加载搜索历史记录
			async loadSearchHistory() {
				try {
					const res = await getSearchHistory(this.userId);
					if (res.code === 200 && res.data) {
						this.searchHistory = res.data;
					}
				} catch (error) {
					console.error('加载搜索历史失败:', error);
				}
			},

			// 保存搜索历史
			async saveSearchHistory(keyword) {
				try {
					// 如果关键词已存在，先移除再添加到最前面
					const index = this.searchHistory.indexOf(keyword);
					if (index !== -1) {
						this.searchHistory.splice(index, 1);
					}
					this.searchHistory.unshift(keyword);

					// 限制历史记录数量
					if (this.searchHistory.length > 10) {
						this.searchHistory = this.searchHistory.slice(0, 10);
					}

					// 调用API保存到服务器
					await saveSearchHistory(this.userId, keyword);
				} catch (error) {
					console.error('保存搜索历史失败:', error);
				}
			},

			// 清空搜索历史
			async clearSearchHistory() {
				try {
					this.searchHistory = [];
					// 这里需要调用API清空服务器上的历史记录
					// 由于后端没有提供清空接口，暂时只做前端清空
					uni.showToast({
						title: '已清空搜索历史',
						icon: 'success'
					});
				} catch (error) {
					console.error('清空搜索历史失败:', error);
				}
			},

			// 选择历史记录项
			selectHistoryItem(item) {
				this.searchKeyword = item;
				this.handleSearch(item);
				this.showHistory = false;
			},

			// 搜索框失去焦点处理
			handleSearchBlur() {
				// 延迟隐藏，以便点击历史记录项能触发
				setTimeout(() => {
					this.showHistory = false;
				}, 200);
			},

			// 格式化商品数据
			formatGoodsItem(item) {
				return {
					id: item.id,
					name: item.name,
					imgSrc: item.imgSrc,
					reason: item.reason,
					originPrice: item.originPrice,
					price: item.price,
					status: item.status,
					// 添加其他可能需要展示的字段
					description: item.description,
					brand: item.brand
				};
			},

			// 设置搜索框placeholder
			setSearchPlaceholder() {
				if (this.recommendedGoods.length > 0) {
					const randomIndex = Math.floor(Math.random() * this.recommendedGoods.length);
					this.searchPlaceholder = `搜索 ${this.recommendedGoods[randomIndex].name}`;
				} else {
					this.searchPlaceholder = '搜索生鲜商品';
				}
			},

			// 切换一级分类
			async changeFirstCategory(typeFirstId, index) {
				this.activeFirstCategoryId = typeFirstId;
				this.activeSecondCategoryId = 'recommend'; // 切换一级分类后默认显示推荐

				// 加载对应二级分类
				this.currentSecondCategories = this.allCategories
					.filter(item => item.typeFirstId === typeFirstId)
					.map(item => ({
						typeSecondId: item.typeSecondId,
						nameSecond: item.nameSecond
					}));

				// 加载该分类下的推荐商品
				await this.loadCurrentRecommendGoods();
				this.currentSecondCategoryName = '推荐';
			},

			// 加载一级分类下所有商品
			async loadFirstCategoryGoods(typeFirstId) {
				try {
					const params = {
						param: {
							typeFirstId: typeFirstId,
							status: 1
						}
					};

					const res = await getGoodsList(params);
					if (res.code === 200) {
						this.currentGoodsList = res.data.map(this.formatGoodsItem); // 直接使用data
						this.currentSecondCategoryName = '全部';
					}
				} catch (error) {
					console.error('加载分类商品失败:', error);
					this.currentGoodsList = [];
				}
			},

			// 换二级分类
			async changeSecondCategory(typeSecondId) {
				this.activeSecondCategoryId = typeSecondId;

				if (typeSecondId === 'recommend') {
					this.currentSecondCategoryName = '推荐';
					await this.loadCurrentRecommendGoods(); // 加载当前分类的推荐商品
				} else if (typeSecondId === 'all') {
					this.currentSecondCategoryName = '全部';
					await this.loadFirstCategoryGoods(this.activeFirstCategoryId);
				} else {
					const category = this.currentSecondCategories.find(
						item => item.typeSecondId === typeSecondId
					);
					this.currentSecondCategoryName = category?.nameSecond || '';
					await this.loadCategoryGoods(this.activeFirstCategoryId, typeSecondId);
				}
			},

			// 加载分类商品
			async loadCategoryGoods(typeFirstId, typeSecondId, isRecommend = false) {
				try {
					const params = {
						param: {
							typeFirstId: typeFirstId,
							status: 1
						}
					};

					if (typeSecondId) {
						params.param.typeSecondId = typeSecondId;
					}

					if (isRecommend) {
						params.param.recommend = 1;
					}

					const res = await getGoodsList(params);
					if (res.code === 200) {
						this.currentGoodsList = res.data.map(this.formatGoodsItem); // 直接使用data
					}
				} catch (error) {
					console.error('加载分类商品失败:', error);
					this.currentGoodsList = [];
				}
			},

			// 修改后的显示全部分类方法 (这个所谓的全部分类是显示所有的一级分类，并不是显示所有的商品)
			async showAllCategories() {
				this.displayedFirstCategories = [...this.allFirstCategories];

				if (this.allFirstCategories.length > 0) {
					await this.changeFirstCategory(this.allFirstCategories[0].typeFirstId, 0);
				}
			},

			// 修改处理搜索方法
			async handleSearch(e) {
				const keyword = e.value || e;
				if (!keyword) {
					if (this.allFirstCategories.length > 0) {
						await this.changeFirstCategory(this.allFirstCategories[0].typeFirstId, 0);
					}
					return;
				}

				try {
					const params = {
						param: {
							name: keyword,
							reason: keyword,
							description: keyword,
							brand: keyword,
							status: 1
						}
					};

					const res = await getGoodsList(params);
					if (res.code === 200) {
						this.currentGoodsList = res.data
							.filter(item => item.status === 1)
							.map(this.formatGoodsItem);

						this.activeSecondCategoryId = 'search';
						this.currentSecondCategoryName = `搜索: ${keyword}`;
						await this.saveSearchHistory(keyword);
					}
				} catch (error) {
					console.error('搜索失败:', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				}
			},

			// 处理清除搜索
			handleClearSearch() {
				// 恢复默认显示
				this.loadRecommendedGoods();
				if (this.allFirstCategories.length > 0) {
					this.changeFirstCategory(this.allFirstCategories[0].typeFirstId, 0);
				}
				this.showCategoryNav = true;
			},

			// 修改搜索输入处理
			handleSearchInput(e) {
				this.searchKeyword = e.value;
			},
			// 处理搜索框获取焦点
			handleSearchFocus() {
				this.showHistory = true;
				// 重新加载历史记录确保数据最新
				this.loadSearchHistory();
			},

			// 加载搜索历史记录 - 添加调试日志
			async loadSearchHistory() {
				try {
					console.log('开始加载搜索历史...');
					const res = await getSearchHistory(this.userId);
					console.log('搜索历史返回数据:', res);

					if (res.code === 200 && res.data) {
						this.searchHistory = res.data;
						console.log('搜索历史加载成功:', this.searchHistory);
					} else {
						console.warn('搜索历史数据格式异常:', res);
					}
				} catch (error) {
					console.error('加载搜索历史失败:', error);
					uni.showToast({
						title: '加载历史记录失败',
						icon: 'none'
					});
				}
			},

			// 获取分类图标
			getCategoryIcon(name) {
				const icons = {
					'肉类': '/static/images/meat.jpg',
					'蛋类': '/static/images/egg.jpg',
					'蔬菜': '/static/images/vegetable.jpg',
					'水果': '/static/images/fruit.jpg'
				};
				return icons[name] || '/static/images/category.jpg';
			},

			// 修改跳转到商品详情
			goToDetail(goodsId) {
				console.log('成功点击:', goodsId); //发现能够输出日志，但是无法跳转
				uni.navigateTo({
					url: `/pages/category/GoodsDetail?id=${goodsId}`
				});
			},

			// 添加到购物车
			async addToCart(goods) {
				await request({
					url: 'shoppingCart/addShoppingCartForCommonGoods?goodsId=' + goods.id,
					method: 'GET'
				})
				uni.showToast({
					title: '已加入购物车',
					icon: 'success'
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 新增搜索历史样式 */
	.search-history {
		position: absolute;
		top: 110%;
		left: 15px;
		right: 15px;
		background-color: #fff;
		border-radius: 0 0 10px 10px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		z-index: 9999;
		padding: 10px;
		max-height: 300px;
		overflow-y: auto;
	}

	.history-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 5px 10px;
		font-size: 14px;
		color: #666;
		border-bottom: 1px solid #eee;
		margin-bottom: 5px;
	}

	.history-list {
		display: flex;
		flex-wrap: wrap;
		padding: 5px;
	}

	.history-item {
		background-color: #f5f5f5;
		padding: 5px 10px;
		margin: 5px;
		border-radius: 15px;
		font-size: 12px;
		color: #333;
	}

	/* 新增搜索按钮样式 */
	.uni-searchbar__cancel {
		color: #ff6700 !important;
	}

	.category-container {
		position: relative;
		overflow: visible;
	}

	.search-bar {
		position: relative;
		padding: 10px 15px;
		background-color: #fff;
		z-index: 1;
	}

	.first-category {
		display: flex;
		white-space: nowrap;
		padding: 10px 0;
		background-color: #fff;

		.category-item {
			display: inline-flex;
			flex-direction: column;
			align-items: center;
			padding: 0 15px;
			flex-shrink: 0;

			&.active {
				.category-name {
					color: #ff6700;
				}
			}

			.category-icon {
				width: 40px;
				height: 40px;
				margin-bottom: 5px;
			}

			.category-name {
				font-size: 12px;
				color: #666;
			}
		}

		.all-category {
			margin-right: 15px;
		}
	}

	.content-container {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.second-category {
		width: 80px;
		background-color: #f5f5f5;

		.second-item {
			padding: 15px 10px;
			font-size: 14px;
			text-align: center;
			color: #666;
			border-left: 3px solid transparent;

			&.active {
				color: #ff6700;
				background-color: #fff;
				border-left: 3px solid #ff6700;
			}

			&.recommend-item {
				font-weight: bold;
			}
		}
	}

	.goods-list {
		flex: 1;
		padding: 10px;
		background-color: #fff;

		.section {
			margin-bottom: 20px;

			.section-title {
				display: block;
				font-size: 16px;
				font-weight: bold;
				margin-bottom: 10px;
				padding-left: 5px;
				border-left: 3px solid #ff6700;
			}
		}

		.goods-column {
			display: flex;
			flex-direction: column;

			.goods-item {
				display: flex;
				margin-bottom: 15px;
				padding-bottom: 15px;
				border-bottom: 1px solid #f5f5f5;
				position: relative;

				.goods-image {
					width: 100px;
					height: 100px;
					border-radius: 5px;
					background-color: #f5f5f5;
					margin-right: 10px;
				}

				.goods-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.goods-name {
						font-size: 14px;
						color: #333;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.goods-reason {
						font-size: 12px;
						color: #ff6700;
						margin: 5px 0;
					}

					.price-container {
						display: flex;
						align-items: center;

						.original-price {
							font-size: 12px;
							color: #999;
							text-decoration: line-through;
							margin-right: 5px;
						}

						.current-price {
							font-size: 16px;
							color: #ff6700;
							font-weight: bold;
						}
					}
				}

				.cart-icon {
					position: absolute;
					right: 10px;
					bottom: 10px;
					width: 30px;
					height: 30px;
					border-radius: 50%;
					background-color: rgba(255, 255, 255, 0.8);
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}
</style>